package com.cloud.job.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cloud.api.domain.job.Addr;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author 杨斌
 * 2025-02-2025-02-11
 */
@Slf4j
@Component
public class ResolveAddress {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private  BaiduConfig config;

    public Addr getAddr(String lat, String lng) {

        String url = UriComponentsBuilder.fromHttpUrl("https://api.map.baidu.com/reverse_geocoding/v3/")
                .queryParam("ak", config.getAk())
                .queryParam("ret_coordtype", config.getRetCoordType())
                .queryParam("coordtype", config.getCoordType())
                .queryParam("extensions_poi", config.getExtensionsPoi())
                .queryParam("extensions_road", config.getExtensionsRoad())
                .queryParam("extensions_town", config.getExtensionsTown())
                .queryParam("output", "json")
                .queryParam("location", lat + "," + lng)
                .toUriString();

        String response = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(response);
        Integer status = jsonObject.getInteger("status");
        Addr addr = null;
        if (status == 0) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject addressComponent = result.getJSONObject("addressComponent");
            String province = addressComponent.getString("province");
            String city = addressComponent.getString("city");
            String district = addressComponent.getString("district");
            String formattedAddressPoi = result.getString("formatted_address_poi");
            addr = new Addr(formattedAddressPoi, province, city,district);
            return addr;
        } else {
            log.error("地址解析异常: " + status);
        }
        return addr;
    }
}
